/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order.virtual;

import cn.hutool.core.util.StrUtil;
import com.lxk.oms.flow.order.OrderContext;
import com.lxk.oms.order.domain.req.CreateOrderReq;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 虚拟SKU上下文填充
 *
 * @author heyi
 * 2024/8/20
 */
@LiteflowComponent(value = FlowVirtualOrderNodeConst.ORDER_FILL_VIRTUAL_SKU_CONTEXT_NODE)
@AllArgsConstructor
public class OrderFillVirtualSkuContextNode extends NodeComponent {
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);


    @Override
    public void process() throws Exception {
        CreateOrderReq params = this.getRequestData();
        log.info("虚拟下单参数:{}", params);
        Long merId = params.getMerId();
        OrderContext context = this.getContextBean(OrderContext.class);
        // 设置SKU信息
        fillVirtualSkuInfo(params, merId, context);
        context.setOrderItemBoList(new ArrayList<>());
        // 设置地址信息
        context.setDeliveryType(params.getDeliveryType());
        // 订单名字最大为200，超过后截取前200
        context.setOrderName(StrUtil.subWithLength(params.getOrderName(), 0, 200));
        context.setCreateType(params.getCreateType());
    }


    /**
     * 设置SKU信息
     *
     * @param params
     * @param context
     */
    private void fillVirtualSkuInfo(CreateOrderReq params, Long merId, OrderContext context) {
        List<CreateOrderReq.CreateVirtualOrderItem> createOrderItemList = params.getVirtualOrderItems();
        List<OrderContext.VirtualSkuInfo> virtualSkuInfos = createOrderItemList.stream().map(item -> {
            OrderContext.VirtualSkuInfo skuInfo = MapstructUtils.convert(item, OrderContext.VirtualSkuInfo.class);
            skuInfo.setMerId(merId);
            return skuInfo;
        }).toList();
        context.setVirtualSkuInfoList(virtualSkuInfos);
    }


}
